<template>
	<div class="category-list">
		<list-title :data="header"></list-title>
		<el-form :model="appInfoForm" :rules="rules" ref="appInfoForm" label-width="200px">
			<el-form-item label="应用名称" prop="data.app_name" style="width: 515px;">
				<el-input v-model="appInfoForm.data.app_name" placeholder="应用名称"></el-input>
			</el-form-item>
			<el-form-item label="名称描述" prop="data.describe" style="width: 515px;">
				<!-- <el-input type="textarea" :rows="3" maxlength="10" placeholder="请输入内容" v-model="appInfoForm.data.describe"></el-input> -->
				<my-textarea ref="mytextarea" :rows=3 :value="appInfoForm.data.describe" @changeTextarea="changeTextarea" :limit="50"></my-textarea>
			</el-form-item>
			<el-form-item label="价格" prop="data.app_year_limit" style="width: 650px;">
				<el-input class="price" v-for="(item, index) in appInfoForm.data.app_year_limit" :key="index" v-model="item.price">
					<template slot="prepend">{{ item.year+'年' }}</template>
				</el-input>
			</el-form-item>
			<el-form-item label="选择分类" prop="data.app_cat_id">
				<el-select v-model="defaultAppCatID" placeholder="请选择分类">
					<el-option v-for="(item, index) in categoryList" :key="index" :label="item.cat_name" :value="parseInt(item.app_cat_id)"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="Icon图标" prop="data.icon" style="width: 378px;">
				<el-input v-model="appInfoForm.data.icon" placeholder="Icon"></el-input>
			</el-form-item>
			<el-form-item label="内网地址" prop="data.app_intranet_url" style="width: 615px;">
				<el-input v-model="appInfoForm.data.app_intranet_url" placeholder="请输入内网地址" class="input-with-select">
					<el-select v-model="appInfoForm.data.app_intranet_agreement" slot="prepend" style="width: 90px">
						<el-option label="http://" value="http://"></el-option>
						<el-option label="https://" value="https://"></el-option>
					</el-select>
				</el-input>
			</el-form-item>
			<el-form-item label="公网地址" prop="data.app_outside_url" style="width: 615px;">
				<el-input v-model="appInfoForm.data.app_outside_url" placeholder="请输入公网地址" class="input-with-select">
					<el-select v-model="appInfoForm.data.app_outside_agreement" slot="prepend" style="width: 90px">
						<el-option label="http://" value="http://"></el-option>
						<el-option label="https://" value="https://"></el-option>
					</el-select>
				</el-input>
			</el-form-item>
			<el-form-item label="预览图" prop="data.preview" style="width: 273px;">
				<!-- <upload :domain="this.$domain.ac" :limit="1" :fileList="appInfoForm.data.preview" :maxSize="20" @insertPic="insertPic" @delPic="delPic"></upload> -->
				<upload-oss 
				:stsdomain="this.$domain.ac" 
				:ossdomain="this.$ossdomain" 
				:appid="'ac'" 
				:limit="1" 
				:fileList="appInfoForm.data.preview" 
				:maxSize="20" 
				@insertFile="insertPic"
				@delFile="delPic">
				</upload-oss>
			</el-form-item>
			<el-form-item label="是否外链" prop="data.outside">
				<el-switch v-model="appInfoForm.data.outside"></el-switch>
			</el-form-item>
			<el-form-item label="打开方式" v-if="appInfoForm.data.outside" prop="data.url_target" style="width: 378px;">
				<el-select v-model="appInfoForm.data.url_target" placeholder="请选择打开方式">
					<el-option label="self" :value="1"></el-option>
					<el-option label="blank" :value="2"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="是否显示" prop="data.display">
				<el-switch v-model="appInfoForm.data.display"></el-switch>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('appInfoForm')" :disabled='appInfoForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='appInfoForm.submitLock'></span>
				</el-button>
				<el-button @click="resetForm('appInfoForm')" v-if='appInfoForm.data.id==0'>重 置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import MyTextarea from "common/Textarea"
import UploadOss from "pc/common/UploadOss"
import {changeToBool, changeUploadFormatBack} from "static/js/common.js"
import {domain} from '@/api';

export default {
	inject: ['reload'],
	data() {
		var checkYearLimit = (rule, value, callback) => {
			for(let i = 0; i<value.length; i++){
				if(value[i].price < 0 || isNaN(value[i].price)){
					return callback(new Error('请填写正确的价格'));
				}
			}
            callback();
        };
		return {
			/*头部数据*/
			header: {
				title: '添加应用',
				reload: false,
				buttons: [
					{
						title: '应用列表',
						type: 'primary',
						pathName: 'pc/devper/app/app-info/AppInfoList',
					}
				]
			},
			/*分类列表数据*/
			categoryList: [],
			/*添加表单数据*/
			appInfoForm: {
				submitLock: false,
				data: {
					id: 0,
					app_name: '',
					describe: '',
					app_year_limit: [
						// {
						// 	'year': 1,//年限
						// 	'price': '1000',//价格
						// },
						// {
						// 	'year': 2,//年限
						// 	'price': '2000',//价格
						// }
					],
					app_cat_id: '',
					icon: '',
					app_intranet_agreement: 'http://',
					app_outside_agreement: 'http://',
					app_intranet_url: '',
					app_outside_url: '',
					preview: [
						// {
						// 	name: 'food.jpeg',
						// 	url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
						// },
						// {
						// 	name: 'girl.jpeg',
						// 	url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1560679288329&di=172c2c82297e0370c719376481a3efd1&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ff47f57c43ebfab555a3e42938d75afc8540b1a3d34124-CXO8Sg_fw658'
						// }
					],
					outside: false,
					url_target: 1,
					display: false,
				}
			},
			rules: {
				data: {
					app_name: [
						{ required: true, message: '请输入应用名称', trigger: 'blur' },
						{ min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
					],
					app_year_limit: [
	                    { validator: checkYearLimit, trigger: 'blur' }
	                ],
					app_cat_id: [
						{ required: true, message: '请选择分类', trigger: 'change' }
					]
				}
			}
		};
	},
	components: {
		ListTitle,
		MyTextarea,
		UploadOss
	},
	created: function() {
		/*获取购买年限*/
		this.getAppYearLimitList()
		/*获取分类数据*/
		this.getCategoryList()
	},
	methods: {
		/*获取购买年限*/
		getAppYearLimitList(){
			this.$baseURL(domain.ac)
			if(this.$api.appYearLimitList != undefined){
				this.$get(this.$api.appYearLimitList).then(res => {
					// console.log(res);
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code === 0){
						if(res.data.data != undefined){
							// console.log(res.data.data)
							this.appInfoForm.data.app_year_limit = []
							Object.keys(res.data.data).forEach((k) => {
								this.appInfoForm.data.app_year_limit.push ({
									year: res.data.data[k].year,
									price: ''
								});
							})

							/*如果是修改，取出旧数据*/
							if(this.$route.query.id){
								this.getAppInfo(this.$route.query.id)
							}
						}
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*获取分类数据*/
		getCategoryList: function(){
			// this.$baseURL('http://super.ac.comdd')
			this.$baseURL(domain.ac)
			if(this.$api.appCategoryList != undefined){
				this.$get(this.$api.appCategoryList, {
					'display': 2
				}).then(res => {
					// console.log(res);
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.categoryList = []
							Object.keys(res.data.data).forEach((k) => {
								this.categoryList.push ({
									app_cat_id: res.data.data[k].app_cat_id,
									cat_name: res.data.data[k].cat_name,
									icon: res.data.data[k].icon,
									display: changeToBool(res.data.data[k].display)
								});
							})
						}
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*取出需要修改的数据*/
		getAppInfo: function(){
			this.header.title = '编辑应用'
			/*取出需要修改的数据*/
			this.appInfoForm.submitLock = true;
			this.$baseURL(domain.ac)
			if(this.$api.modifyAppinfo != undefined){
				this.$get(this.$api.modifyAppinfo, {
					'id': this.$route.query.id
				}).then(res => {
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code == 0){
						// console.log(res.data.data)
						this.appInfoForm.data.id = res.data.data.app_info_id
						this.appInfoForm.data.app_name = res.data.data.app_name
						this.$refs.mytextarea.initDescribe(res.data.data.describe)//初始化子组件的值
						this.appInfoForm.data.app_cat_id = parseInt(res.data.data.app_cat_id)
						this.appInfoForm.data.icon = res.data.data.icon
						if(res.data.data.app_intranet_url.indexOf("http://") != -1){
							this.appInfoForm.data.app_intranet_agreement = "http://"
							this.appInfoForm.data.app_intranet_url = res.data.data.app_intranet_url.substring(7)
						}else if(res.data.data.app_intranet_url.indexOf("https://") != -1){
							this.appInfoForm.data.app_intranet_agreement = "https://"
							this.appInfoForm.data.app_intranet_url = res.data.data.app_intranet_url.substring(8)
						}else{
							this.appInfoForm.data.app_intranet_agreement = "http://"
							this.appInfoForm.data.app_intranet_url = res.data.data.app_intranet_url
						}
						if(res.data.data.app_outside_url.indexOf("http://") != -1){
							this.appInfoForm.data.app_outside_agreement = "http://"
							this.appInfoForm.data.app_outside_url = res.data.data.app_outside_url.substring(7)
						}else if(res.data.data.app_outside_url.indexOf("https://") != -1){
							this.appInfoForm.data.app_outside_agreement = "https://"
							this.appInfoForm.data.app_outside_url = res.data.data.app_outside_url.substring(8)
						}else{
							this.appInfoForm.data.app_outside_agreement = "http://"
							this.appInfoForm.data.app_outside_url = res.data.data.app_outside_url
						}
						this.appInfoForm.data.preview = changeUploadFormatBack(res.data.data.preview)
						this.appInfoForm.data.outside = changeToBool(res.data.data.outside)
						this.appInfoForm.data.url_target = parseInt(res.data.data.url_target)
						this.appInfoForm.data.display = changeToBool(res.data.data.display)

						/*填充价格*/
						for(let i=0; i<this.appInfoForm.data.app_year_limit.length; i++){
							Object.keys(res.data.data.price).forEach((k) => {
								if(this.appInfoForm.data.app_year_limit[i].year == res.data.data.price[k].year){
									this.appInfoForm.data.app_year_limit[i].price = parseInt(res.data.data.price[k].price)
								}
							})
						}

					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
					this.appInfoForm.submitLock = false;
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*修改文本域的内容，给子组件调用*/
		changeTextarea(v){
			this.appInfoForm.data.describe = v
		},
		/*提交添加、修改表单*/
		submitForm(formName) {
			if(!this.appInfoForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.appInfoForm.submitLock = true;
						/*添加、修改分类*/
						let apiUrl = this.$api.addAppInfo//默认是添加
						if(this.appInfoForm.data.id > 0){//修改
							apiUrl = this.$api.modifyAppinfo
						}
						this.$baseURL(domain.ac)
						if(apiUrl != undefined){
							this.$post(apiUrl, {
								AppInfo: this.appInfoForm.data
							}).then(res => {
								// console.log(res);
								/*成功*/
								if(res.data.code == 0){
									this.$refs.mytextarea.initDescribe('')
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'success'
									});
									if(this.appInfoForm.data.id > 0){//修改的话，返回列表
										this.$router.go(-1)	
									}else{//添加就清空表单
										this.$refs[formName].resetFields();
									}
								}else{
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'error'
									});
								}
								this.appInfoForm.submitLock = false;
							});
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*插入上传的图片*/
		insertPic(list){
			// this.appInfoForm.data.preview = this.appInfoForm.data.preview.concat(list)
			for(let i=0; i<list.length; i++){
				this.appInfoForm.data.preview.push(
					{
						name: '',
						url:  list[i].url
					}
				)
			}
		},
		/*删除上传的图片*/
		delPic(index){
			this.appInfoForm.data.preview.splice(index, 1)
		},
	},
	computed: {
		/*角色的默认值，是否在列表中存在，如果不存在，则不显示，避免显示数字的尴尬*/
		defaultAppCatID: {
			get: function () {
				for(let i=0; i<this.categoryList.length; i++){
					if(this.appInfoForm.data.app_cat_id == this.categoryList[i].app_cat_id){
						return this.appInfoForm.data.app_cat_id
					}
				}
				return ''
			},
			set: function (val) {
				this.appInfoForm.data.app_cat_id = val
			}
		}
	}
};
</script>

<style lang="stylus" scoped>
.category-list
	form
		margin-top: 10px
		.line
			text-align: center
		.price
			width: 135px
			margin-right: 5px
			margin-bottom: 5px
		.price:nth-child(3n)
			margin-right: 0px
</style>